package com.jewelry.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jewelry.entity.Product;
import com.jewelry.entity.Shoucang;
import com.jewelry.entity.User;
import com.jewelry.mapper.ShoucangMapper;
import com.jewelry.service.ProductService;
import com.jewelry.service.ShoucangService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("showcang")
public class ShowcangController {
    @Autowired
    private ShoucangService shoucangService;
    @Autowired
    private ShoucangMapper shoucangMapper;
    @Autowired
    private ProductService productService;
    @PostMapping("/addsc")
    public Map addSC(@RequestParam Integer productId, HttpSession session){
        Map map = new HashMap();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        //判断数据库有没有
        QueryWrapper<Shoucang> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("suser_id", userId)
                .eq("spro_id", productId);
        Shoucang one = shoucangMapper.selectOne(queryWrapper);
        if (one == null){
            Shoucang shoucang = new Shoucang();
            shoucang.setSproId(productId);
            shoucang.setSuserId(userId);
            shoucangService.save(shoucang);
            map.put("message","success");
        }else {
            map.put("message","errorByBoth");
        }

        return map;
    }

    @DeleteMapping("{productId}")
    public Map deleteShoucang(@PathVariable("productId") Integer productId) {
        Map<String, String> map = new HashMap<>();
        try {
            QueryWrapper<Shoucang> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("spro_id", productId);
            shoucangService.remove(queryWrapper);
            map.put("message", "success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "error");
        }
        return map;
    }

    @GetMapping("/all")
    public List<Product> showAllwdsc(HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        QueryWrapper<Shoucang> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("suser_id", userId);
        List<Shoucang> shoucangs = shoucangMapper.selectList(queryWrapper);

        List<Product> productList = new ArrayList<>(); // 创建一个新的List集合用于存储product对象

        for (Shoucang shoucang : shoucangs) {
            Integer sproId = shoucang.getSproId(); // 获取每个元素的sproId
            Product product = productService.getById(sproId); // 调用getById方法获取对应的product对象
            productList.add(product); // 将product对象添加到新的List集合中
        }
        return productList;
    }
}
